use syn::{File, Item, ItemImpl, Type};
use quote::quote;
use quote::ToTokens;
use tempfile::NamedTempFile;
use std::process::Command;
use std::env;
use std::fs;
use std::io::Write;
use std::collections::VecDeque;

fn main() {
    // 获取传递的文件名
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        eprintln!("Usage: merge-impl/target/debug/fix-unclosed-delimiter -- <filename>");
        return;
    }
    let filename = &args[1];

    // 读取文件内容
    let content = fs::read_to_string(filename).expect("Unable to read file");

    let lines: Vec<&str> = content.lines().collect();

    // 检测并修复未闭合的分隔符
    let mut fixed_content = String::new();
    let mut stack = VecDeque::new();
    let mut indent_level = 0;

    for line in lines {
        fixed_content.push_str(line);
        fixed_content.push('\n');

        // 检测分隔符
        for ch in line.chars() {
            match ch {
                '{' => {
                    stack.push_back('{');
                    indent_level += 1;
                }
                '}' => {
                    if let Some(top) = stack.back() {
                        if *top == '{' {
                            stack.pop_back();
                            indent_level -= 1;
                        }
                    }
                }
                _ => {}
            }
        }
    }

    // 修复未闭合的分隔符
    while let Some(ch) = stack.pop_back() {
        if ch == '{' {
            fixed_content.push_str(&format!("{}}}\n", "    ".repeat(indent_level)));
            indent_level -= 1;
        }
    }
   
    // 将过滤后的代码写入临时文件
    let mut temp_file = NamedTempFile::new().expect("Failed to create temp file!");
    writeln!(temp_file, "{}", fixed_content).expect("Failed to write code into temp file!");

    // 使用 rustfmt 格式化代码
    let temp_path = temp_file.path().to_str().unwrap();
    Command::new("rustfmt")
        .arg(temp_path)
        .status()
        .expect("Failed to call rustfmt");

    // 格式化生成的代码
    let formatted_code = fs::read_to_string(temp_path).expect("Failed to read back formatted file!");
    
    // 输出结果
    println!("{}", formatted_code);
}
